<template>
  <PageDialog
    :title="title"
    v-model:visible="showDialog"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
  >
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="table-top-msg">
          <div class="table-top-msg-left">可选择</div>
          <div class="table-top-msg-left">
            <el-button @click="removeRight">右移</el-button>
          </div>
        </div>
        <DialogTable
          ref="leftTableInfoRef"
          :refresh="leftTableInfo.refresh"
          :init-curpage="leftTableInfo.initCurpage"
          v-model:data="leftTableInfo.data"
          :api="leftTableInfo.api"
          :reserve-selection="true"
          :listen-height="false"
          :check-box="true"
          check-box-fixed="right"
          v-model:query="leftFilterInfo.query"
          :field-list="leftTableInfo.fieldList"
          :handle="leftTableInfo.handle"
          @handleEvent="leftHandleEvent"
        >
          <template v-slot:col-storeBatchNumber="scope">
            <StoreBatchNumberTag :row="scope.row" />
          </template>
        </DialogTable>
      </el-col>
      <el-col :span="12">
        <div class="table-top-msg">
          <div class="table-top-msg-right">
            <el-button @click="removeLeft">左移</el-button>
          </div>
          <div class="table-top-msg-right">已选择</div>
        </div>
        <DialogTable
          ref="rightTableInfoRef"
          v-model:data="rightTableInfo.data"
          :reserve-selection="true"
          :listen-height="false"
          :pager="false"
          :check-box="true"
          checkBoxFixed="left"
          :field-list="rightTableInfo.fieldList"
          :handle="rightTableInfo.handle"
          @handleEvent="rightHandleEvent"
        >
          <template v-slot:col-storeBatchNumber="scope">
            <StoreBatchNumberTag :row="scope.row" />
          </template>
          <template v-slot:col-scrapReason="scope">
            <el-input
              v-model="scope.row.scrapReason"
              :maxlength="25"
              @input="(e) => (scope.row.scrapReason = validSe(e))"
            />
          </template>
        </DialogTable>
      </el-col>
    </el-row>
  </PageDialog>
</template>
<script setup name="batchIndividual">
import { getCustomizeSetting } from "@/api/customize";
import StoreBatchNumberTag from "@/views/stock/components/StoreBatchNumberTag";
import _ from "lodash";
const { proxy } = getCurrentInstance();
const emits = defineEmits();
const props = defineProps({
  title: {
    type: String,
    default: "个体详情",
  },
  leftApi: {
    type: Function,
  },
  rightApi: {
    type: Function,
  },
  visible: {
    type: Boolean,
  },
  showPrice: {
    type: Boolean,
  },

  isGetRightList: {
    type: Boolean,
    default: false,
  },
  isRequest: {
    type: Boolean,
    default: false,
  },

  leftQuery: {
    type: Object,
    default: function () {
      return {};
    },
  },
  rightQuery: {
    type: Object,
    default: function () {
      return {};
    },
  },
  leftTableKey: {
    type: String,
    default: "",
  },
  rightTableKey: {
    type: String,
    default: "",
  },
  details: {
    type: Array,
    default: function () {
      return [];
    },
  },
  sysGroup: {
    type: Array,
    default: function () {
      return [];
    },
  },
  scrapReason: {
    //报废出库用
    type: Boolean,
    default: false,
  },
  isAddEstimationStockBusiness: {
    type: Boolean,
    default: false,
  },
  consumeRevokeDimensionType: {
    type: Number || String,
    default: 1,
  },
  codeType: {
    // 原厂码 3 唯一码(个体码)2
    type: Number || String,
    default: '',
  },
});
const groupKeysFilter = ref({
  1:['batchNumber','productionDate','validityDate','price','supplierId','storeBatchNumber','isConsignBusiness','isEstimationStockBusiness'],
  2:['price','supplierId','storeBatchNumber','isConsignBusiness','isEstimationStockBusiness'],
  3:[],
})
const info = ref({});
// 过滤相关配置
const leftFilterInfo = ref({
  query: {
    queryMap: {
      ...props.leftQuery.queryMap,
    },
    queryParams: {
      stockAvailableCalcQtyGt: 0,
      ...props.leftQuery.queryParams,
    },
    customizeUserVO: {},
  },
});
// 表格相关
const leftTableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  fieldList: [],
});
const rightTableInfo = ref({
  data: [],
  fieldList: [],
  selections: [],
});
const rightFilterInfo = ref({
  query: {
    queryMap: {
      ...props.rightQuery.queryMap,
    },
    queryParams: {
      ...props.rightQuery.queryParams,
    },
    customizeUserVO: {},
  },
});
// 弹窗相关
const dialogInfo = ref({
  btLoading: false,
  width: "90%",
  btList: [
    { label: "关闭", event: handleClose, show: true },
    { label: "保存", event: handleSave, show: true },
  ],
});
const showDialog = computed({
  get() {
    return props.visible;
  },
  set(val) {
    emits("update:visible", val); // 更新父组件visible
  },
});
function leftHandleEvent(event, data) {
  if (event === "list") {
    data.forEach((item) => {
      item.depotStockIdClone = item.depotStockId;
      // item.depotStockId = item.id
    });
    leftTableInfo.value.data = data;
  }
  if (event === "tableCheck") {
    leftTableInfo.value.selections = data;
  }
}
function rightHandleEvent(event, data) {
  switch (event) {
    case "tableCheck":
      rightTableInfo.value.selections = data;
      break;
  }
}
function getleftList() {
  leftTableInfo.value.api = props.leftApi;
  leftTableInfo.value.refresh = Math.random();
}
// 关闭弹窗前的回调
function handleClose() {
  showDialog.value = false;
  emits("reset");
}
async function removeRight() {
  //左边往右移
  let selections = leftTableInfo.value.selections;
  if (selections.length) {
    rightTableInfo.value.data = rightTableInfo.value.data.concat(selections);
    let ids = rightTableInfo.value.data.map((item) => item.id.toString());
    leftFilterInfo.value.query.queryMap.id.value = ids.length
      ? ids.toString()
      : "";
  }
  getleftList();
  proxy.$refs["leftTableInfoRef"].clearSelection();
}
async function removeLeft() {
  //右边往左移
  let selections = rightTableInfo.value.selections;
  if (selections.length) {
    rightTableInfo.value.data = rightTableInfo.value.data.filter(
      (item) => !selections.includes(item)
    );
    let ids = [];
    if (rightTableInfo.value.data.length) {
      ids = rightTableInfo.value.data.map((item) => item.id.toString());
    }
    leftFilterInfo.value.query.queryMap.id.value = ids.length
      ? ids.toString()
      : "";
  }
  getleftList();
  proxy.$refs["rightTableInfoRef"].clearSelection();
}
function handleSave() {
  if (rightTableInfo.value.data) {
    rightTableInfo.value.data.forEach((item) => {
      if (props.consumeRevokeDimensionType == 1) {
        item._key =
          item.orderNo +
          "-" +
          item.batchNumber +
          "-" +
          item.productionDate +
          "-" +
          item.validityDate +
          "-" +
          item.storeBatchNumber +
          "-" +
          item.supplierId +
          "-" +
          item.price +
          "-" +
          item.isConsignBusiness +
          "-" +
          item.isEstimationStockBusiness;
      }
      if (props.consumeRevokeDimensionType == 2) {
        item._key =
        item.orderNo +
          "-" +
          item.storeBatchNumber +
          "-" +
          item.supplierId +
          "-" +
          item.price +
          "-" +
          item.isConsignBusiness +
          "-" +
          item.isEstimationStockBusiness;
      }
      if (props.consumeRevokeDimensionType == 3) {

        item._key = item.orderNo;
      }
      let str = "";
      props.sysGroup.forEach((i) => {
        if (
          !groupKeysFilter.value[props.consumeRevokeDimensionType + ""].includes(i)
        ) {
          if (i === "productionDate" || i === "validityDate") {
            str = str + (item[i] || "1900-01-01") + "";
          } else {
            str = str + item[i] + "";
          }
        }
      });
      item.groupKey = str;
    });
  }
  emits("callback", rightTableInfo.value.data);
  handleClose();
}
function getLeftCustomize() {
  let param = { tableKey: props.leftTableKey };
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data;
      leftFilterInfo.value.query.customizeUserVO = data;
      leftTableInfo.value.fieldList = proxy.$fn.setFieldList(
        leftTableInfo.value.fieldList,
        data.detail
      );
      leftTableInfo.value.fieldList.forEach((item) => {
        if (item.value === "storeBatchNumber") {
          item["type"] = "slot";
        } else if (props.codeType === 2) {
            if (
              item.value === 'factoryMainCode' ||
              item.value === 'factorySubCode'
            ) {
              item.hidden = true
            }
          } else if (props.codeType === 3) {
            if (item.value === 'uniqueCode') {
              item.hidden = true
            }
          }
      });
      getleftList();
    }
  });
}
function getRightCustomize() {
  let param = { tableKey: props.rightTableKey };
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data;
      rightFilterInfo.value.query.customizeUserVO = data;
      rightTableInfo.value.fieldList = proxy.$fn.setFieldList(
        rightTableInfo.value.fieldList,
        data.detail
      );
      rightTableInfo.value.fieldList.forEach((item) => {
        if (item.value === "storeBatchNumber") {
          item["type"] = "slot";
        }
        else if (props.codeType === 2) {
            if (
              item.value === 'factoryMainCode' ||
              item.value === 'factorySubCode'
            ) {
              item.hidden = true
            }
          } else if (props.codeType === 3) {
            if (item.value === 'uniqueCode') {
              item.hidden = true
            }
          }
      });
      if (props.details && props.details.length) {
        rightTableInfo.value.data = proxy.$fn.deepClone(props.details);
      }
      if (props.isGetRightList && props.isRequest && !info.value.details) {
        getRightList();
      }
    }
  });
}
function getRightList() {
  props.rightApi(rightFilterInfo.value.query).then((resp) => {
    if (resp && resp.success && resp.data.length) {
      let data = resp.data;
      info.value.details = data;
      rightTableInfo.value.data = data;
    }
  });
}

let obj = {
  price: {
    label: "单价",
    value: "price",
    type: "column",
    componentType: "price",
    permission: !props.showPrice,
    formatter: proxy.$fn.TripartiteMethod,
    show: false,
    hidden: true,
  },
  sumAmount: {
    label: "总金额",
    value: "sumAmount",
    type: "column",
    componentType: "price",
    permission: !props.showPrice,
    formatter: proxy.$fn.TripartiteMethod,
    show: false,
    hidden: true,
  },
  showPrice: {
    label: "展示价格",
    value: "showPrice",
    type: "column",
    componentType: "price",
    permission: !props.showPrice,
    formatter: proxy.$fn.TripartiteMethod,
    show: false,
    hidden: true,
  },
  defaultSupplierPrice: {
    label: "默认供应商价格",
    value: "defaultSupplierPrice",
    permission: !props.showPrice,
    componentType: "price",
    type: "column",
    formatter: proxy.$fn.TripartiteMethod,
    show: false,
    hidden: true,
  },
  commonName: {
    label: "通用名称",
    value: "commonName",
    componentType: "input",
    show: false,
    hidden: true,
  },
  orderNo: {
    label: "消耗单号",
    value: "orderNo",
    componentType: "text",
    show: false,
    hidden: true,
  },
};
let scrapReason = props.scrapReason
  ? {
      label: "报废原因",
      value: "scrapReason",
      minWidth: "150px",
      type: "slot",
      hidden: true,
    }
  : "";
leftTableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
});
rightTableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
  scrapReason,
});
getLeftCustomize();
getRightCustomize();
</script>
<style lang="scss" scoped>
.table-top-msg {
  width: 100%;
  display: flex;
  align-items: center;
  .table-top-msg-left,
  .table-top-msg-right {
    width: 50%;
    display: flex;
    align-items: center;
  }
  .table-top-msg-left {
    justify-content: flex-end;
  }
  .table-top-msg-right {
    justify-content: flex-start;
  }
}
</style>
>
